//
//  getBookInfo.swift
//  ZTC_Final
//
//  Created by xy Man on 2022/5/25.
//

import Foundation
import WebKit

func getBooksFromURL()->Void{
    // 获取网络信息
    let url:URL = URL(string: "http://zy.whu.edu.cn/cs/api/book/list")!

    // 初始化数据库
    let sqlite = SQLiteManager.sharedInstance
    
    if !sqlite.openDB(){return}
    //创建书籍信息表
    let createBookTable = "CREATE TABLE IF NOT exists book('title'  text primary key, 'ISBN' text, 'kind' text, 'price' double, 'author' text, 'description' text, 'pic_path' text)"
    if !sqlite.execNoneQuerySQL(sql: createBookTable){sqlite.closeDB(); return}
    else{
        print("建库成功")
    }
    
    URLSession.shared.dataTask(with: url) { (objectData, response, error) in
           guard error == nil else {
               print("网络出错:\(error!.localizedDescription)")
               return
           }
           
           guard objectData != nil else {
               print("数据为空：")
               return
           }
           
           do {
               // 序列化请求下来的Data对象objectData成jsonData
               let jsonData = try JSONSerialization.jsonObject(with: objectData!, options: .mutableContainers)
               // 将json格式文件转换为Dictionary<String,AnyObject>类文件
               let dic = jsonData as? Dictionary<String,AnyObject> ?? [:]
//               print(dic)
               // 取出字典中的result字段
               let result = dic["result"] as? Array<Dictionary<String,AnyObject>> ?? []
//               print(result)
               // 将每本书的内容分别提取出来，进行数据库的存储或文件的存储
               for book in result{
                   
                   let id:String=book["id"] as? String ?? "no_book"
                   let author:String=book["author"] as? String ?? ""
                   let title:String=book["title"] as? String ?? ""
                   let code:String=book["code"] as? String ?? ""
                   let kind:String=book["kind"] as? String ?? ""
                   let pic:String=book["pic"] as? String ?? ""
                   let description:String=book["description"] as? String ?? ""
                   let price:Double=Double(book["price"] as? String ?? "") ?? 0.0
                   let pathImg:String=FileManager.default.urls(for:.documentDirectory,in:.userDomainMask).first!.appendingPathComponent("\(id).jpg").path
                   
                   // 将文件下载到项目document文件夹中
                   // downloadImg(url:URL(string: pic)!, filename: id)
                   // 将书籍信息添加到书籍信息表中
                   let addBookSql = "REPLACE INTO book VALUES('\(title)', '\(code)', '\(kind)', '\(price)', '\(author)', '\(description)', '\(pic)');"
                   if !sqlite.execNoneQuerySQL(sql: addBookSql){sqlite.closeDB(); return}
               }
           } catch {
               print("解析出错")
           }
       }.resume()
        print("executed")
      
}

func downloadImg(url:URL,filename:String) ->Void {
    URLSession.shared.dataTask(with: url) { (objectData, response, error) in
           guard error == nil else {
               print("网络出错:\(error!.localizedDescription)")
               return
           }
           
           guard objectData != nil else {
               print("数据为空：")
               return
           }
        if let objectData = objectData{
            do{
                let target=FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("\(filename).jpg")
                try objectData.write(to: target)
            }
            catch{
                print("写文件失败！")
            }
        }
    }.resume()

}
